<template>
  <div style="height: 100%">
    <div>
      <el-row :gutter="1">
        <el-col :span="8">
          <el-form ref="form" :model="form">
            <el-form-item>
              <!-- <el-button size="mini" type="primary" @click="screeningData"
                >查 询</el-button
              > -->
              <el-button size="mini" type="success" @click="openDialogAddLine"
                >新增路线</el-button
              >
              <el-button style="padding: 0; border: 0">
                <el-upload
                  action="/上传文件的接口"
                  :on-change="onChange"
                  :auto-upload="false"
                  :show-file-list="false"
                  accept=".xls, .xlsx"
                  class="upload"
                >
                  <el-button size="mini" type="success">批量导入</el-button>
                </el-upload>
              </el-button>
              <el-button size="mini" type="warning" @click="exportExcel"
                >批量导出</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <el-table :data="tableData" height="75%" @row-dblclick="dblClickRow">
      <!-- <el-table-column
        prop="ID"
        label="路线编号"
        align="center"
      ></el-table-column> -->
      <el-table-column
        prop="LICENSE_PLATE"
        label="负责车辆"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="StartTime"
        label="起始时间"
        align="center"
      ></el-table-column>
      <!-- <el-table-column
        prop="StartTime"
        label="起始点位"
        align="center"
      ></el-table-column> -->
      <el-table-column
        prop="WorkPoint"
        label="途径点位个数"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="ISPLANED"
        label="规划状态"
        align="center"
        :formatter="formatterISPLANED"
      ></el-table-column>
      <el-table-column label="规划操作" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.ISPLANED === '0'"
            type="text"
            @click="handleSubmitPlan(scope.$index, scope.row)"
            >开始规划</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="途径点位" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="openDialogPointList(scope.$index, scope.row)"
            >途经点位列表</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="编辑" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="openDialogAddPoint(scope.$index, scope.row)"
            >新增途径点</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleShowMap(scope.$index, scope.row)"
            >计划与实际路线对比</el-button
          >
          <!-- <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            @click="handleDelete(scope.$index, scope.row)"
            style="color: red"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import '@/assets/css/common.css'
import export2Excel from '@/utils/exportExcel/index.js'
import mapicon from '@/assets/img/marker/mapicon.png'
import eventBus from '@/eventBus.js'


export default {
  data () {
    return {
      marker: null,
      map: null,
      mapZoom: 16,

      currentPage: 1, //初始页
      pageSize: 10,    //    每页的数据
      originalData: [],
      tableData: [],
      isVisibleEdit: false,
      form: {
        tag: '',
        LONGITUDE: '',
        LATITUDE: '',
        LOCATION: '',
        stime: '',
        etime: '',
        wtime: '',
        lineData: {}
      },
      formLine: {
        slat: '',
        slng: '',
        StartTime: '05:00',
        elng: '',
        elat: '',
        carID: '',
        pointsData: []
      },
      formMapPoint: {
        LONGITUDE: '',
        LATITUDE: '',
        LOCATION: '',
        show: false,
        tag: ''
      },
      addDialogTitle: '',
      // addLineDialogTitle: '',
      addLineDialogShow: false,
      addPointDialogShow: false,
      rubbishPointDetailDialogShow: false,
      rubbishPointsData: [],
      optionsCar: [],
      dataLoad: [],
      selectCarID: ''
    }
  },
  created () {
    
    // 显示底部列表
    eventBus.$on('UpdateTable', () => {
      this.getlistdata();
    })
  },
  mounted () {
    this.getlistdata();
  },
  methods: {
    formatterISPLANED (row) {
      if (row.ISPLANED === '1') {
        return '已完成规划'
      } else {
        return '未规划'
      }
    },
    openDialogAddLine () {
      eventBus.$emit('openDialogAddLine')
    },
    openDialogAddPoint (index, row) {
      eventBus.$emit('openDialogAddPoint', row)
    },
    openDialogPointList (index, row) {
      eventBus.$emit('openDialogPointList', row.PlanLinePoints)
    },
    async handleSubmitPlan (index, row) {
      const loading = this.$loading({
        lock: true,
        text: '正在路线规划中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      var url = '/DataListCompany/CreateRubbishPlan?lineID=' + row.ID
      this.$axios({
        url: url,
        method: 'get',
      }).then(res => {
        loading.close()
        if (res.data) {
          this.getlistdata();
          this.$message.success('操作成功')
        } else {
          this.$message.error('路线规划失败')
        }
      })
    },
    handleShowMap (index, row) {
      this.$router.push({ path: '/ShowRoute', query: { VID: row.VID, carName: row.LICENSE_PLATE } })
    },
    dblClickRow (row) {
      eventBus.$emit('mapLocaltionPlan', row.PlanLinePoints)
    },
    // 导入Excel
    // 导入Excel
    onChange (file, fileList) {
      //  console.log(fileList);
      this.fileData = file; // 保存当前选择文件
      this.readExcel(); // 调用读取数据的方法
    },
    // 读取数据
    readExcel (e) {
      let that = this;
      const files = that.fileData;
      console.log(files);
      if (!files) {
        //如果没有文件
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader();
      console.log(fileReader)
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          //  console.log(ev.target)
          //  console.log(this);
          const workbook = this.XLSX.read(data, {
            type: "binary"// 以字符编码的方式解析
          });

          if (workbook.SheetNames.length > 0) {
            workbook.SheetNames.forEach(element => {
              const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[element]); //生成json表格内容
              this.bulkLoad(ws)
            });
            
          } else {
            this.$message.error("未读取到表格内容");
          }
        } catch (e) {
          console.log(e)
          return false;
        }
      };
      // 如果为原生 input 则应是 files[0]
      fileReader.readAsBinaryString(files.raw);
    },
    bulkLoad (ws) {
      var pointList = []
      ws.forEach(element => {
        var pointInfo = {
          PointName: element.PointName,
          PointID: element.PointID,
          LONGITUDE: element.LONGITUDE,
          LATITUDE: element.LATITUDE,
          Stime: element.Stime,
          Etime: element.Etime,
          Wtime: element.Wtime,
        }
        pointList.push(pointInfo)
      });
      var lineInfo = {
        VID: ws[0].VID,
        StartTime: ws[0].StartTime,
        StartLONGITUDE: ws[0].StartLONGITUDE,
        StartLATITUDE: ws[0].StartLATITUDE,
        EndLONGITUDE: ws[0].EndLONGITUDE,
        EndLATITUDE: ws[0].EndLATITUDE,
        PointList: pointList
      }
      eventBus.$emit('excelLoad', lineInfo)
      // this.dataLoad.push(lineInfo)
    },
    // 导出Excel
    // 导出Excel
    exportExcel () {
      const newArr = this.tableData
      let excelData = [];
      newArr.forEach((val) => {
        val.PlanLinePoints.forEach((obj) => {
          obj.LICENSE_PLATE = val.LICENSE_PLATE
          obj.StartTime = val.StartTime
          obj.WorkPoint = val.WorkPoint
          obj.YjTime = obj.Stime + " - " + obj.Etime
          excelData.push(obj)
        })
      })
      console.log("点位信息：" + excelData)
      let excelName = '路线规划'
      const tHeader = ['负责车辆', '起始时间', '途径点位个数', '途径点位名称', '预计到达时间', '预计作业时长（秒）']
      const filterVal = ['LICENSE_PLATE', 'StartTime', 'WorkPoint', 'PointName', 'YjTime', 'Wtime']
      export2Excel(tHeader, filterVal, excelData, excelName)
    },
    // exportExcel () {
    //   let excelName = '点位信息'
    //   const tHeader = ['点位名称', '经度', '纬度', '位置', '区域ID', '类型']
    //   const filterVal = ['NAME', 'LONGITUDE', 'LATITUDE', 'LOCATION', 'CLIENT_NO', 'TYPE_NAME']
    //   export2Excel(tHeader, filterVal, this.tableData, excelName)
    // },
    //获取列表
    async getlistdata () {
      var url = 'DataListCompany/GetVehicleRubbishPlan'
      const { data } = await this.$Http.get(url)
      this.originalData = data
      eventBus.$emit('getPlanDrawPolygon', this.originalData)
      this.screeningData()
    },
    // 模糊查询
    screeningData () {
      this.currentPage = 1;
      this.tableData = this.originalData
      // if (this.select.name) this.tableData = this.tableData.filter(item => item.NAME.includes(this.select.name))
      // console.log(this.select.name)
      // eventBus.$emit('mapData_Water', this.tableData)
    },
    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage;
      // console.log(this.currentPage)
      // this.$set(this.query, 'pageIndex', val);
      // this.getlistdata();
    },
    handleSizeChange (size) {
      this.pageSize = size;
      console.log(this.pageSize)
    },
  }
}
</script>
<style>
.tangram-suggestion {
  z-index: 9999;
}
</style>